package cn.fly.identification.config.server;

import cn.fly.identification.service.IdentificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Component
@ServerEndpoint(value = "/identification/{sid}")
public class WebSocketServer {

    private static final String RESULT_SUCCESS = "识别成功";
    private static final String RESULT_ERROR = "识别失败";

    private static final String IS_NOT_DETE = "人脸检测失败";
    private static final String IS_NOT_LIVING= "活体检测失败";

    private static IdentificationService identificationService;

    @Autowired
    public void setIdentificationService(IdentificationService identificationService) {
        WebSocketServer.identificationService = identificationService;
    }


    private static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        WebSocketServer.stringRedisTemplate = stringRedisTemplate;
    }

    private static Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端: " + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    @OnMessage(maxMessageSize = 1048576)
    public void onMessage(String baseImg, @PathParam("sid") String sid){
        System.out.println(baseImg);

        AtomicBoolean isDete = new AtomicBoolean(false);
        AtomicBoolean isLiving = new AtomicBoolean(false);

        isDete = identificationService.checkDete(baseImg);

        if (isDete.get())
            isLiving = identificationService.checkLiving(baseImg);
        else
            sendToClient(sid, IS_NOT_DETE);

        if (isLiving.get()) {
            AtomicBoolean identification = identificationService.identify(baseImg);

            if (identification.get())
                sendToClient(sid, RESULT_SUCCESS);
            else
                sendToClient(sid, RESULT_ERROR);
        } else if (isDete.get())
            sendToClient(sid, IS_NOT_LIVING);

    }

    @OnClose
    public void onClose(@PathParam("sid") String sid){
        System.out.println("连接断开: " + sid);
        sessionMap.remove(sid);
    }

    @OnError
    public void onError(Session session, Throwable thr) {
        System.out.println("WebSocket 出现错误: " + thr.getMessage());
        // 在这里执行错误处理逻辑
    }

    public void sendToClient(String sid, String result){
        Session session = sessionMap.get(sid);
        try {
            session.getBasicRemote().sendText(result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
